package com.leinao.media.handler;

import com.leinao.media.constants.MediaConstant;
import com.leinao.media.entity.Result;
import com.leinao.media.exception.MediaException;
import com.leinao.media.exception.NotPermissionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *
 * @author zhangyu
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 权限异常
     */
    @ExceptionHandler(NotPermissionException.class)
    public Result<Void> handleNotPermissionException(NotPermissionException e, HttpServletRequest request) {
        log.error("请求地址'{}',权限校验失败'{}'", request.getRequestURI(), e.getMessage());
        return Result.fail(HttpStatus.FORBIDDEN.value(), "没有访问权限");
    }

    /**
     * 流媒体异常
     */
    @ExceptionHandler(MediaException.class)
    public Result<Void> handleServiceException(MediaException e, HttpServletRequest request) {
        log.error("请求地址'{}',发生流媒体异常.", request.getRequestURI(), e);
        return Result.fail(MediaConstant.FAIL, e.getMessage());
    }

    /**
     * 未知异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e, HttpServletRequest request) {
        log.error("请求地址'{}',发生未知异常.", request.getRequestURI(), e);
        return Result.fail(MediaConstant.FAIL, e.getMessage());
    }

}
